﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Windows.Forms;
using Ersur.DevTeam;
using Ersur.Properties;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraEditors;
using Karbel;


namespace Ersur
{
    public partial class MainForm : RibbonForm
    {
        public int WhoAmI;
        public XForm ActiveXForm = null;

        public MainForm()
        {
            InitializeComponent();
        }

        #region Bluetooth
        //string portData = string.Empty;
        System.IO.Ports.SerialPort port;
        delegate void OnBarcodeReadHandler(int text);
        #endregion

        #region ShowForm
        public XForm GetActiveForm(Type type, params object[] prm)
        {
            XForm frm;
            string hash = GetHash(type, prm);

            forms.TryGetValue(hash, out frm);

            if (frm != null)
                if (!frm.IsDisposed)
                {
                    frm.Activate();
                    return frm;
                }
                else
                    forms.Remove(hash);

            return null;
        }

        public Dictionary<string, XForm> forms = new Dictionary<string, XForm>();

        private string GetHash(Type type, object[] prm)
        {
            string prmHash = "";
            foreach (object o in prm)
                prmHash += o.GetHashCode();

            return type.GetHashCode() + "." + prmHash;
        }

        public XForm ShowMdiChildForm(Type type, params object[] prm)
        {
            XForm frm = GetActiveForm(type, prm);

            if (frm != null)
            {
                ActiveXForm = frm;
                return frm;
            }

            try
            {
                if (type.BaseType == typeof(XPopupForm))
                {
                    using (XPopupForm popup = (XPopupForm)Activator.CreateInstance(type, prm))
                    {
                        ActiveXForm = popup;
                        frm = popup;
                        popup.ShowDialog();
                    }
                }
                else
                {
                    frm = (XForm)Activator.CreateInstance(type, prm);
                    frm.MdiParent = this;
                    frm.WindowState = FormWindowState.Maximized;
                    string hash = GetHash(type, prm);
                    forms.Add(hash, frm);
                    ActiveXForm = frm;
                    frm.Show();

                }
            }
            catch (Exception Ex)
            {
                XtraMessageBox.Show(Ex.InnerException.ToString());
            }

            return frm;
        } 
        #endregion

        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F12 && e.Control)
            {
                string message = "Connection String=" + Settings.ConnectionString + "\r\n\r\n";
                message += "Config File Path=" + Settings.ConfigFilePath;
                Clipboard.SetText(message);
                MessageBox.Show(message);
            }

            if (e.KeyCode == Keys.F10 && e.Control)
            {
                ErsurServices.ErsurServicesSoapClient es = new ErsurServices.ErsurServicesSoapClient();
                string result = es.Do("ers", Settings.TerminalNo);
                Data.DataManager.ExecuteDataTableByQuery(result);

                MessageBox.Show("OK");
            }
        }

        public string Info
        {
            set
            {
                string message = value;
                message = message.Replace("\r\n", " ");
                lblInfo.Caption = "[" + DateTime.Now.ToString("HH:mm:ss") + "] " + message;
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.KeyDown += MainForm_KeyDown;


            btnNewOrder.ItemClick += btnNewOrder_ItemClick;
            btnOrders.ItemClick += btnOrders_ItemClick;
            btnProducts.ItemClick += btnProducts_ItemClick;
            btnSettings.ItemClick += btnSettings_ItemClick;
            btnClear.ItemClick += btnClear_ItemClick;
            btnSync.ItemClick += btnSync_ItemClick;
            btnSendEmail.ItemClick += btnSendEmail_ItemClick;

            FormClosing += new FormClosingEventHandler(MainForm_FormClosing);


            //using (Login login = new Login())
            //{
            //    DialogResult drLogin = login.ShowDialog();

            //    if (drLogin != System.Windows.Forms.DialogResult.OK)
            //    {
            //        Application.Exit();
            //        return;
            //    }
            //}

            AppSession.MainForm = this;
            Settings.Init();
            Data.Init(Settings.ConnectionString);

            ribbon.ToolbarLocation = RibbonQuickAccessToolbarLocation.Hidden;

            btnConnect.PerformClick();

            //gvProduct.Columns["Article"].ColumnEdit = GetAutoCompGLE(ds.Product, "Article");
            //((RepositoryItemGridLookUpEdit)gvProduct.Columns["Article"].ColumnEdit).ProcessNewValue += new ProcessNewValueEventHandler(ri_ProcessNewValue2);            
            //gvProduct.Properties.ProcessNewValue += new ProcessNewValueEventHandler(ri_ProcessNewValue2);
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                port.Close();

            }
            catch { }
        }  
         
        //public void ri_ProcessNewValue2(object sender, ProcessNewValueEventArgs e)
        //{
        //    string newEntry = e.DisplayValue.ToString();
        //    if (newEntry != string.Empty)
        //    {
        //        ((DataTable)((GridLookUpEdit)sender).Properties.DataSource).Rows.Add(newEntry);
        //        e.Handled = true;
        //    }
        //}
         
     
         
        //public string ScriptDatabase()
        //{
        //    //string a = ScriptDatabase();
        //    var sb = new StringBuilder();

        //    var server = new Server(@".\sqlexpress");
        //    var databse = server.Databases["ersur"];

        //    var scripter = new Scripter(server);
        //    scripter.Options.ScriptDrops = true;
        //    scripter.Options.WithDependencies = true;
        //    scripter.Options.IncludeHeaders = true;

        //    //And so on ....


        //    var smoObjects = new Urn[1];
        //    foreach (Table t in databse.Tables)
        //    {
        //        smoObjects[0] = t.Urn;
        //        if (t.IsSystemObject == false)
        //        {
        //            StringCollection sc = scripter.Script(smoObjects);

        //            foreach (var st in sc)
        //            {
        //                sb.Append(st);
        //            }
        //        }
        //    }
        //    foreach (Microsoft.SqlServer.Management.Smo.View t in databse.Views)
        //    {
        //        smoObjects[0] = t.Urn;
        //        if (t.IsSystemObject == false)
        //        {
        //            StringCollection sc = scripter.Script(smoObjects);

        //            foreach (var st in sc)
        //            {
        //                sb.Append(st);
        //            }
        //        }
        //    }

        //    foreach (StoredProcedure t in databse.StoredProcedures)
        //    {
        //        smoObjects[0] = t.Urn;
        //        if (t.IsSystemObject == false)
        //        {
        //            StringCollection sc = scripter.Script(smoObjects);

        //            foreach (var st in sc)
        //            {
        //                sb.Append(st);
        //            }
        //        }
        //    }
        //    return sb.ToString();
        //}

        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string data = port.ReadExisting();

            if (data.EndsWith("\r\n"))
            {
                data = data.Replace("\r\n", "");

                Info = "Barcode: '" + data + "'";

                //son hane parity ve tip alanları atılınca geri kalan çıplak barkod
               int barcode = int.Parse(data.Substring(0, data.Length - 1));
 
                if (ActiveXForm != null)
                    ActiveXForm.FireBarcodeRead(barcode);
            }  
        }

        #region Buttons
        private void btnProducts_ItemClick(object sender, ItemClickEventArgs e)
        {
            ShowMdiChildForm(typeof(Products));
        }

        private void btnClear_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (Clear clear = new Clear())
            {
                if (clear.ShowDialog() == DialogResult.OK)
                {
                    Data.DB.Clear();
                }
            }
        }
         
        private void btnNewOrder_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (NewOrder newOrder = new NewOrder())
            {
                DialogResult dr = newOrder.ShowDialog();

                if (dr == DialogResult.OK)
                {
                    ErsurDB.OrderRow orderRow = Data.DB.Order.NewOrderRow();

                    orderRow.Brand  = newOrder.Brand;
                    orderRow.Address  = newOrder.Address;
                    orderRow.Phone = newOrder.Phone;
                    orderRow.Fair = Settings.FairName;
                    orderRow.Season = Settings.Season;
                    orderRow.Notes = Settings.Notes;
                    orderRow.Email = newOrder.Email;
                    orderRow.Contact = newOrder.Contact;
                    orderRow.Cancelled = false;
                    orderRow.EditDate = DateTime.Now;

                    Data.DB.Order.Rows.Add(orderRow);

                    Data.Save();
                }
            }
        }

        private void btnOrders_ItemClick(object sender, ItemClickEventArgs e)
        {
            ShowMdiChildForm(typeof(Orders));
        }

        private void btnConnect_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            this.btnConnect.CheckedChanged -= btnConnect_CheckedChanged;

            if (btnConnect.Checked)
            {
                try
                {
                    port = new System.IO.Ports.SerialPort("COM" + Settings.ComPort);
                    port.BaudRate = 57600;
                    port.DataBits = 8;
                    port.Parity = System.IO.Ports.Parity.None;
                    port.StopBits = StopBits.One;
                    port.Handshake = Handshake.None;
                    port.DtrEnable = true;
                    if (!port.IsOpen)
                        port.Open();

                    port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
                
                    Info = "Connected successfully.";
                }
                catch (Exception ex)
                {
                    btnConnect.Checked = false;
                    Info = "Connection error !!!:" + ex.Message;
                }
            }
            else
            {
                if (port != null && port.IsOpen)
                    port.Close();
            }

            if (btnConnect.Checked)
            {
                btnConnect.Caption = "Connected to barcode reader.";
                btnConnect.LargeGlyph = Resources.Connected;
                btnConnect.Enabled = false;
            }
            else
            {
                btnConnect.Caption = "Connect to barcode reader !!!";
                btnConnect.LargeGlyph = Resources.Disconnected;
                btnConnect.Enabled = true;
            }

            this.btnConnect.CheckedChanged += btnConnect_CheckedChanged;
        }

        private void btnSettings_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (Settings settings = new Settings())
            {
                settings.ShowDialog();
            }
        }

        private void btnSync_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            Data.Save();

            DataRow[] drs = Data.DB.Order.Select("SyncDate is null");
            Info = Data.Sync(drs);

            this.Cursor = Cursors.Default;
        }
         
        private void btnSendEmail_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            Data.Save();
             
            DataRow[] drs = Data.DB.Order.Select("eMailDate is null");

            Info = Data.SendEmail(drs);
            this.Cursor = Cursors.Default;
        }

        #endregion

        private void btnLists_ItemClick(object sender, ItemClickEventArgs e)
        {
            ShowMdiChildForm(typeof(Entities));
        }
    }
}